package org.example.completed.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.completed.domain.Active;
import org.example.completed.domain.ActivityReservation;
import org.example.completed.domain.User;
import org.example.completed.mapper.ActiveMapper;
import org.example.completed.mapper.ActivityReservationMapper;
import org.example.completed.mapper.UserMapper;
import org.example.completed.service.ActivityReservationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ActivityReservationServiceImpl extends ServiceImpl<ActivityReservationMapper, ActivityReservation> implements ActivityReservationService {

    @Autowired
    private ActiveMapper activeMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public ActivityReservation getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<ActivityReservation> listAll() {
        return baseMapper.selectList(null);
    }

    @Override
    public boolean saveReservation(ActivityReservation reservation) {
        return save(reservation);
    }

    @Override
    public boolean signUp(String activityId, String userId, String phone) {
        Active active = activeMapper.selectById(activityId);

        //报名人数是否小于报名总人数限制
        if (active.getApplyNumber() < active.getTotalNumber()){
            active.setApplyNumber(active.getApplyNumber()+1);
            activeMapper.updateById(active);
        }else {
            throw new IllegalArgumentException("报名人数已满");
        }
        User user = userMapper.selectById(userId);
        if (active == null) {
            throw new IllegalArgumentException("预约活动不存在");
        }
        if (user == null) {
            throw new IllegalArgumentException("报名用户信息不存在");
        }
        ActivityReservation reservation = new ActivityReservation();
        reservation.setActivityId(activityId);
        reservation.setUserId(userId);
        reservation.setName(active.getName());
        reservation.setImageUrl(active.getImageUrl());
        reservation.setDescription(active.getDescription());
        reservation.setStartTime(active.getStartTime());
        reservation.setEndTime(active.getEndTime());
        reservation.setPhone(phone);
        reservation.setUserAcoount(user.getUserAcoount());
        return baseMapper.insert(reservation) > 0;
    }

    @Override
    public List<ActivityReservation> listByActivityId(String activityId) {
        QueryWrapper<ActivityReservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("activity_id", activityId);
        return baseMapper.selectList(queryWrapper);
    }
}